package com.crop.back.common.utils;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
@Component
public class TraceIdGenerator {

    private final RedisUtil redisUtil;

    private static final String PREFIX = "TR"; // Trace的前缀
    private static final String DATE_FORMAT = "yyyyMMdd";
    private static final int SEQUENCE_LENGTH = 6; // 序列号长度

    public String generateTraceId(Long batchId, String productCategory) {
        // 1. 获取日期部分
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern(DATE_FORMAT));

        // 2. 获取品类代码(两位)
        String categoryCode = getCategoryCode(productCategory); // 如: VG-蔬菜, FR-水果

        // 3. 获取序列号(6位，每天从000001开始)
        String sequence = getSequence();

        // 4. 组装: TR + 日期 + 品类代码 + 序列号
        // 示例: TR20240318VG000001
        return PREFIX + date + categoryCode + sequence;
    }

    public String generateTraceId(Long batchId) {
        // 1. 获取日期部分
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern(DATE_FORMAT));

        // 2. 获取品类代码(两位)
        String categoryCode = "DE"; // 如: VG-蔬菜, FR-水果 DE-默认

        // 3. 获取序列号(6位，每天从000001开始)
        String sequence = getSequence();

        // 4. 组装: TR + 日期 + 品类代码 + 序列号
        // 示例: TR20240318VG000001
        return PREFIX + date + categoryCode + sequence;
    }

    public String getCategoryCode(String category) {
        // 根据产品分类返回对应代码
        Map<String, String> categoryMap = new HashMap<>();
        categoryMap.put("蔬菜", "VG");
        categoryMap.put("水果", "FR");
        categoryMap.put("粮食", "GR");
        categoryMap.put("肉类", "MT");

        return categoryMap.getOrDefault(category, "OT");
    }

    private String getSequence() {
        // 从Redis获取当天序列号并自增
        String key = "trace_sequence:" + LocalDate.now().format(DateTimeFormatter.ofPattern(DATE_FORMAT));
        Long sequence = redisUtil.incr(key, 1);

        // 首次设置过期时间(第二天凌晨过期)
        if (sequence == 1) {
            redisUtil.expireWithTimeUnit(key, 24, TimeUnit.HOURS);
        }

        // 格式化为6位数字
        return String.format("%06d", sequence);
    }
}
